import { useState, useRef, useEffect } from "react";
import { Image, Button } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import useCommonTable from "@/hooks/useCommonTable";
import {
  fetchList,
  updateStatus,
  add,
  update,
  remove,
  pageQueryArticles,
} from "@/api/mall";
import { fetchList as fetchTemplateList } from "@/api/freeTemplate";

import { history } from "umi";
import {
  articlesCategoryOptions,
  paymentTypeOptions,
  disableStatusOptions,
} from "@/const";
import useUpdateStatus from "@/hooks/useUpdateStatus";
import {
  ProFormSelect,
  ProFormRadio,
  ProFormDigit,
  ProFormDependency,
  ProFormText,
} from "@ant-design/pro-form";

export default () => {
  const actionRef = useRef();
  const columns = [
    {
      title: "商品名称",
      dataIndex: "title",
      width: 150,
    },
    {
      title: "兑换积分",
      dataIndex: "integralPrice",
      width: 150,
      search: false,
    },
    {
      title: "兑换金额",
      dataIndex: "price",
      width: 150,
      search: false,
    },
    {
      title: "库存",
      width: 150,
      dataIndex: "exchangeInventory",
      search: false,
    },
    {
      title: "已兑数量",
      dataIndex: "name",
      width: 150,
      search: false,
      render: (_, record) => {
        const res =
          (record.exchangeInventory || 0) - (record.surplusInventory || 0);
        return res < 0 ? 0 : res;
      },
    },
    {
      title: "是否上架",
      dataIndex: "onTheShelf",
      valueType: "select",
      width: 150,
      fieldProps: {
        options: disableStatusOptions,
      },
      render: (_, record) => {
        return useUpdateStatus(
          updateStatus,
          record,
          actionRef,
          null,
          false,
          "onTheShelf",
          {
            articlesCategory: record.articlesCategory,
            rasGoodsId: record.rasGoodsId,
          }
        );
      },
    },
  ];

  const [freeTemplateList, setFreeTemplateList] = useState([]);
  const [shopList, setShopList] = useState([]);
  const [specList, setSpecList] = useState([]); // 规格
  const [maxInventory, setMaxInventory] = useState(0);

  const getFreeTemplateList = async () => {
    const res = await fetchTemplateList({
      pageNum: 1,
      pageSize: 999999,
    });
    if (res.data) {
      setFreeTemplateList(res.data);
    }
  };

  useEffect(() => {
    getShopList();
    getFreeTemplateList();
  }, []);

  const getShopList = async (articlesId, specificationId) => {
    const res = await pageQueryArticles({
      pageNum: 1,
      pageSize: 99999,
    });
    const bookList = res.data?.map((item) => {
      return {
        ...item,
        label: item.title,
        value: item.articlesId,
      };
    });
    setShopList(bookList);
    if (articlesId) {
      const shopObj = bookList.find((item) => item.value === articlesId);
      const arr = shopObj.mallSpecificationVOS || [];
      setSpecList(arr);
      if (specificationId) {
        const specObj = arr.find((item) => item.id === specificationId);
        setMaxInventory(specObj.inventory);
      }
    }
  };

  const renderFormItem = ({ formRef }) => {
    return (
      <>
        <ProFormSelect
          name="articlesId"
          label="关联商品"
          allowClear
          fieldProps={{
            options: shopList,
            showSearch: true,
            filterOption: (input, option) => {
              return (
                option.label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
              );
            },
            onChange: (value) => {
              const shopObj = shopList.find((item) => item.value === value);
              setSpecList(shopObj.mallSpecificationVOS || []);
              formRef.current.setFieldsValue({
                specificationId: "",
                title: shopObj.title || shopObj.name,
                picture: shopObj.picture,
                articlesCategory: shopObj.articlesCategory,
              });
            },
          }}
          rules={[{ required: true, message: "请选择商品" }]}
        />

        <ProFormText hidden name="title" />
        <ProFormText hidden name="picture" />
        <ProFormText hidden name="articlesCategory" />

        <ProFormSelect
          name="freeTemplateId"
          label="运费模板"
          allowClear
          fieldProps={{
            options: freeTemplateList,
            fieldNames: {
              label: "tempName",
              value: "id",
            },
          }}
          rules={[{ required: true, message: "请选择运费模板" }]}
        />

        <ProFormSelect
          name="specificationId"
          label="商品规格"
          allowClear
          fieldProps={{
            options: specList,
            fieldNames: {
              label: "specification",
              value: "id",
            },
            onChange: (id) => {
              const specObj = specList.find((item) => item.id === id);
              setMaxInventory(specObj.inventory);
            },
          }}
          rules={[{ required: true, message: "请选择商品规格" }]}
        />

        <ProFormRadio.Group
          label="兑换方式"
          name="paymentType"
          options={paymentTypeOptions}
          rules={[{ required: true, message: "请选择兑换方式" }]}
        />
        <ProFormDigit
          label="积分"
          name="integralPrice"
          placeholder="请输入积分"
          min={1}
          rules={[{ required: true, message: "请输入积分" }]}
        />

        <ProFormDigit
          label="兑换库存"
          name="exchangeInventory"
          placeholder="请输入兑换库存"
          min={1}
          max={maxInventory}
          rules={[{ required: true, message: "请输入兑换库存" }]}
        />

        <ProFormDependency name={["paymentType"]}>
          {({ paymentType }) => {
            return (
              paymentType === 2 && (
                <ProFormDigit
                  label="金额"
                  name="price"
                  placeholder="请输入金额"
                  min={1}
                  fieldProps={{
                    precision: 2,
                  }}
                  rules={[{ required: true, message: "请输入金额" }]}
                />
              )
            );
          }}
        </ProFormDependency>
      </>
    );
  };

  return (
    <PageContainer>
      {useCommonTable({
        actionRef,
        title: "",
        columns,
        formInitialValues: {
          paymentType: 1,
        },
        add,
        update,
        transformPostData: (values) => {
          return {
            ...values,
            price: values.price || 0,
          };
        },
        onEdit: (record, formRef) => {
          getShopList(record.articlesId, record.specificationId);
        },
        renderFormItem,
        modalWidth: 700,
        fetchList,
        remove,
        actionColumnWidth: 200,
        showCheckbox: false,
        labelCol: { span: 4 },
      })}
    </PageContainer>
  );
};
